package com.gyms.fragment;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnBannerClickListener;
import com.classic.okhttp.AppChangeUtils;
import com.classic.okhttp.beans.HVCitiesBean;
import com.classic.okhttp.beans.HVClickInfoBean;
import com.classic.okhttp.beans.HVHomePageItemBean;
import com.classic.okhttp.beans.HVProjectBean;
import com.classic.okhttp.beans.HVVenueBean;
import com.classic.okhttp.enums.Enum;
import com.classic.okhttp.services.ICommonService;
import com.classic.okhttp.services.IVenueService;
import com.classic.okhttp.zmoumall.http.ObjectCallback;
import com.google.gson.Gson;
import com.gyms.R;
import com.gyms.activity.CityActivity;
import com.gyms.activity.GymDetailActivity;
import com.gyms.activity.MainActivity;
import com.gyms.activity.ProductDetailsActivity;
import com.gyms.activity.SearchActivity;
import com.gyms.activity.SearchResultActivity;
import com.gyms.adapter.AllSpAdapter;
import com.gyms.adapter.GymsRecyclertAdapter;
import com.gyms.adapter.NetworkImageHolderView;
import com.gyms.adapter.ViewPagerAdapter;
import com.gyms.base.BaseFragment;
import com.gyms.bean.ThreeWheelBean;
import com.gyms.behavior.FabBehavior;
import com.gyms.constant.Constants;
import com.gyms.manager.AllProjectManger;
import com.gyms.manager.BannerIntentManger;
import com.gyms.manager.CommonDialogUtils;
import com.gyms.manager.LocationManger;
import com.gyms.manager.StatisticsManager;
import com.gyms.view.bottomview.RecommendDialog;
import com.gyms.view.wheel.ThreeWheelTimeDialog;
import com.gyms.view.wheel.WheelDialog;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cache.ACache;
import constant.EventConstant;
import constant.FileConstant;
import myInterface.OnItemClickLitener;
import refresh.PtrClassicFrameLayout;
import refresh.PtrDefaultHandler;
import refresh.PtrFrameLayout;
import refresh.PtrHandler;
import utils.AnimotionUtils;
import utils.DateUtil;
import utils.FileUtils;
import utils.ScreenUtils;
import utils.SizeUtils;
import utils.StringUtils;
import weight.ComDialog;
import weight.UiEvent;
import weight.head_foot_recyclerView.EndlessRecyclerOnScrollListener;
import weight.head_foot_recyclerView.HeaderAndFooterRecyclerViewAdapter;
import weight.head_foot_recyclerView.LoadingFooter;
import weight.head_foot_recyclerView.RecyclerViewStateUtils;


/**
 * 场馆fragment
 * ltx
 */
public class GymnasiumsFragment extends BaseFragment implements OnBannerClickListener, View.OnClickListener {

    RelativeLayout mRlTabLayout;
    private ImageView mIvImgRight;//右边的搜索按钮
    TextView mTvFindPlace;
    LinearLayout mViewTab;
    @BindView(R.id.pf_home)
    PtrClassicFrameLayout mPfHome;
    @BindView(R.id.rl_tile)
    RelativeLayout mLlCommonTitle;
    @BindView(R.id.fab_back_to_top)
    FloatingActionButton mBackToTop;


    private TextView mCityTv;//定位城市
    private TextView mTitleView;//标题的View
    private ImageView mIvSearch;//定位城市
    ConvenientBanner mCbBanner;//banner

    /* ----------   全部运动相关 -------*/
    private List<HVProjectBean> mHVProjectBeans = new ArrayList<>();
    /**
     * 全有运动总的页数
     */
    private int pageCount;
    /**
     * 所有运动每一页显示的个数
     */
    private int pageSize = 10;
    /**
     * 所有运动当前显示的是第几页
     */
    private int curIndex = 0;

    ViewPager mVpSPAll;
    LinearLayout mLlSpDos;
    LinearLayout mRlSpAll;
    LinearLayout mLlTime;

    private List<View> mSpPagerList;

    private HVProjectBean mHVProjectBean;//默认是第一个

    private final static String ALL_SPORT = "全部";

    private ViewPagerAdapter mVPAllSport;//所有运动的
    /* ----------   全部运动相关 -------*/
    /* ----------   全部场馆 -------*/
    private GymsRecyclertAdapter mAllGymAdapter;
    @BindView(R.id.lv_all_gym)
    RecyclerView mLvAllGym;

    /* ----------   平移相关 -------*/
    TextView mViewSelected;
    private int singleDistance;//单个TextView的宽度
    private int curPos = 0;//当前位置
    private int nextPos;//下一个位置
    /* ----------   所有场馆 -------*/
    private List<HVVenueBean> mHVVenueBeans = new ArrayList<>();

    private HVCitiesBean mHVCitiesBean;

    TextView mTvDay;

    TextView mTvtime;
    //获取地址
    private File file, mCurrCity;

    private List<HVCitiesBean> mHVCitiesBeens = new ArrayList<>();//城市列表数据源
    private Gson mGson;

    private AllProjectManger mAllProjectManger;
    //banner
    private List<HVHomePageItemBean> mHVHomePageItemBeans = new ArrayList<>();
    private BannerIntentManger bannerIntentManger;//banner 的点击事件

    /*隐藏标题显示相关*/
    private int height;//相对的参考高度
    private ThreeWheelBean wheelBean;
    private LocationManger mLocationManger;//定位的manger

    private MainActivity mMainActivity;
    private final static String TODAY="今天";

    //点击类型 是否全部预定 课程
    private final static int sBOOK_GYM=1;//预定场馆
    private final static int sBOOK_PRODUCT=2;//预定课程
    private final static int sBOOK_ALL=0;//全部
    private View mHomeHeadView;

    //刷新 加载更多
    private boolean isRefresh=true;//是否是刷新
    private boolean isCanLoadMore=true;
    private LinearLayoutManager mLinearLayoutManager;
    private FabBehavior mFabBehavior;
    private int mScreenHight=0;//屏幕高度

    private int mScrollHight=0;//向上滚动的高度

    @Override
    protected int getLayoutResId() {
        return R.layout.search_gymnasiums;
    }

    @Override
    protected void initView() {
        mMainActivity= (MainActivity) getActivity();
        ScreenUtils.translateStatusBar(getActivity());
        mCityTv = (TextView) mRootView.findViewById(R.id.tv_city);
        mTitleView = (TextView) mRootView.findViewById(R.id.tv_title);
        mIvImgRight = (ImageView) mRootView.findViewById(R.id.iv_search);
        initHead();
        mTitleView.setText(AppChangeUtils.mAppTitle);
        setCityRightDrable();
        initAllGym();
        mLvAllGym.setFocusable(false);//解决默认不置顶
        //计算单个TextView的宽度
        measureDistace();
        ViewGroup.LayoutParams lp = mViewSelected.getLayoutParams();
        lp.width = singleDistance;
        lp.height = ViewGroup.LayoutParams.MATCH_PARENT;
        mViewSelected.setLayoutParams(lp);
        //获取当前的日期
        SimpleDateFormat formatter = new SimpleDateFormat("MM月dd日");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        //tvDay
        String day = StringUtils.stringAdd2Space("今天(" + str + "）");
        SpannableStringBuilder sb = new SpannableStringBuilder(day); // 包装字体内容
        ForegroundColorSpan fcs = new ForegroundColorSpan(getResources().getColor(R.color.c_333333)); // 设置字体颜色
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(SizeUtils.dp2px(mContext, 16),false);  // 设置字体大小
        sb.setSpan(fcs, 0, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        sb.setSpan(ass, 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvDay.setText(sb);
        //初始化一个默认时间
        if (wheelBean == null) {
            wheelBean = new ThreeWheelBean();
            wheelBean.setDateStr(TODAY);
            wheelBean.setStartTimeStr(ThreeWheelTimeDialog.minEndTime);
            wheelBean.setEndTimeStr(ThreeWheelTimeDialog.maxEndTime);
            int timeStart =DateUtil.getTimesMorning();//当天的0:0:0
            int timeEnd = DateUtil.getTimesNight()-1;//当天的23:59:59
            wheelBean.setStartTimeInt(timeStart);
            wheelBean.setEndTimeLInt(timeEnd);
        }
        mGson = new Gson();
        mAllProjectManger = AllProjectManger.getInstance();//初始化Manger
        mLocationManger= LocationManger.getInstance(getActivity());
        bannerIntentManger=new BannerIntentManger(getContext());
        initBanner();
        initAllSport();
        initBehavior();
    }

    private void initBehavior() {
        mFabBehavior = FabBehavior.from(mBackToTop);
        mScreenHight=ScreenUtils.getScreenHeight(getActivity());
        mFabBehavior.setScreenHight(mScreenHight);
    }

    private void initHead() {
        mHomeHeadView=View.inflate(mContext,R.layout.ll_home_head,null);
        mCbBanner= (ConvenientBanner) mHomeHeadView.findViewById(R.id.cb_Banner);
        mViewTab= (LinearLayout) mHomeHeadView.findViewById(R.id.view_tab);
        mTvtime= (TextView) mHomeHeadView.findViewById(R.id.tv_day_time);
        mTvFindPlace= (TextView) mHomeHeadView.findViewById(R.id.tv_find_place);
        mRlSpAll= (LinearLayout) mHomeHeadView.findViewById(R.id.rl_sp_all);
        mVpSPAll= (ViewPager) mHomeHeadView.findViewById(R.id.vp_sp_all);
        mLlSpDos= (LinearLayout) mHomeHeadView.findViewById(R.id.ll_sp_dos);
        mRlTabLayout= (RelativeLayout) mHomeHeadView.findViewById(R.id.rl_tab_layout);
        mLlTime= (LinearLayout) mHomeHeadView.findViewById(R.id.ll_Time);
        mViewSelected= (TextView) mHomeHeadView.findViewById(R.id.view_selected);
        mTvDay= (TextView) mHomeHeadView.findViewById(R.id.tv_day);
    }

    private void doShowRecommendDia(HVHomePageItemBean response) {
        RecommendDialog recommendDialog=new RecommendDialog(getActivity());
        recommendDialog.show();
        recommendDialog.setHVHomePageItemBean(response);
    }


    /**
     * 初始化所有运动
     */

    private void initAllSport() {
        mSpPagerList = new ArrayList<>();//存放glideView的list
        mVPAllSport= new ViewPagerAdapter(mSpPagerList);
        //设置适配器
        mVpSPAll.setAdapter(mVPAllSport);//全部运动
    }

    @Override
    protected void initListener() {
        mCityTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, CityActivity.class);
                mContext.startActivity(intent);
                getActivity().overridePendingTransition(R.anim.activity_open, R.anim.activity_stay);
            }
        });
        mTvFindPlace.setOnClickListener(this);


        for (int i = 0; i < mViewTab.getChildCount(); i++) {
            final TextView mTabText = (TextView) mViewTab.getChildAt(i);
            mTabText.setTag(i);
            mTabText.setOnClickListener(new View.OnClickListener() {
                int pos = (int) mTabText.getTag();//当前点击的位置

                @Override
                public void onClick(View v) {
                    if (pos != mViewTab.getChildCount() - 1) {//显示时间隐藏全部
                        mRlSpAll.setVisibility(View.GONE);
                        mLlTime.setVisibility(View.VISIBLE);
                    } else {//显示全部隐藏时间
                        mLlTime.setVisibility(View.GONE);
                        mRlSpAll.setVisibility(View.VISIBLE);
                    }
                    if (pos != 4) {//最后一是全部
                        if (null != mHVProjectBeans && pos < mHVProjectBeans.size()) {//防止数据越界
                            mHVProjectBean = mHVProjectBeans.get(pos);
                        }
                        mViewSelected.setText(null == mHVProjectBean ? "" : mHVProjectBean.getProjectName());
                    } else {
                        mViewSelected.setText(ALL_SPORT);//显示全部
                    }
                    doMoveSelected(pos);
                }
            });

            mBackToTop.setOnClickListener(this);
        }
        //注册EventBus
        EventBus.getDefault().register(this);

        mPfHome.disableWhenHorizontalMove(true);//解决和ViewPager的冲突

        mPfHome.setPtrHandler(new PtrHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                refreshGymList();
                getProjects();
                getHomepageContent();
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });

        mTvDay.setOnClickListener(selectDateListener);
        mTvtime.setOnClickListener(selectDateListener);
        /**
         * title透明显示相关
         */
        ViewTreeObserver vto = mCbBanner.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mCbBanner.getViewTreeObserver().removeGlobalOnLayoutListener(
                        this);
                height = mCbBanner.getHeight();
            }
        });

        mCbBanner.setOnBannerClickListener(this);
        mLvAllGym.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mScrollHight=mScrollHight+dy;
                mFabBehavior.setScrollHight(mScrollHight);
                if(mScrollHight<mScreenHight){//保证第一页不会出现
                    AnimotionUtils.onHide(mBackToTop);
                }

                if (getScollYDistance() <= 0) {
                    //静止并处于最顶端状态
                    mLlCommonTitle.setBackgroundColor(Color.argb(0, 250, 250, 250));
                } else if (getScollYDistance() > 0 && getScollYDistance()<height / 2) {//滑动在0-400距离的时候
                    float scale = (float) getScollYDistance() / (height / 2);
                    float alpha = (255 * scale);
                    mLlCommonTitle.setBackgroundColor(Color.argb((int) alpha, 3, 150, 235));
                } else {
                    mLlCommonTitle.setBackgroundColor(Color.argb(255, 3, 150, 235));
                }
            }
        });
    }

    @Override
    protected void processLogic() {
        file = new File(Environment.getExternalStorageDirectory(), FileConstant.FILE_CITY);//存储城市的file
        mCurrCity = new File(Environment.getExternalStorageDirectory(), FileConstant.FILE_SELCT_CITY);//当前选择的城市存储的file
        mHVCitiesBean = mMyApplication.mHVCitiesBean;
        if (null == mHVCitiesBean) {//全局的数据为null就直接去本地文件的数据
            getLocalCurrCity();
            if (null == mHVCitiesBean) {//本地无数据 去网络down
                getCityData();
            } else {//本地的cityBean有值就给全局赋值
                doFullCurCity();
            }
        }else{//缓存里的数据
            doFullCurCity();
        }
        mMainActivity.loadingView.show();
        getVenueList();
        getProjects();
        getHomepageContent();
        getHomeBanner();
    }

    /**
     * 获取首页弹出式banner
     */

    private void getHomeBanner() {

        ICommonService.getHomeBanner(getActivity(), mLocationManger.getCityCode(), false, new ObjectCallback<HVHomePageItemBean>() {
            @Override
            public void onSuccess(HVHomePageItemBean response, String message) {
                if(null!=response){
                    String mBannerId= ACache.get(mContext).getAsString(Constants.ACACHE_HOME_BANNNER);
                    if(mBannerId==null||!mBannerId.equals(String.valueOf(response.getClickInfo().getBannerId()))){//缓存三天的时间 如果过时了或者有新的图片ID
                        doShowRecommendDia(response);
                    }
                }
            }

            @Override
            public void onErrorT(int code, HVHomePageItemBean response, String errorMessage) {

            }

            @Override
            public void onHttpErrorCall(int statusCode) {

            }
        });
    }

    /**
     * 填充当前城市 且刷新课程数据
     */

    private void doFullCurCity() {
        mCityTv.setText(mHVCitiesBean.getName());
        EventBus.getDefault().post(new UiEvent(EventConstant.S_CITY_COURSE, mHVCitiesBean));
        mMyApplication.mHVCitiesBean = mHVCitiesBean;
        doCheckCurCity(mHVCitiesBean);
    }

    /**
     * 检测定位是否是当前的城市
     * @param HVCitiesBean
     */

    private void doCheckCurCity(HVCitiesBean HVCitiesBean) {
        String curCity=HVCitiesBean.getName();
        final String mLocationCity=mLocationManger.getLocationCity();
        if(!mLocationCity.contains(curCity)&&mLocationManger.isLocationSuc()){//在定位成功的情况下
            final ComDialog dialog = CommonDialogUtils.dialog(getActivity(),getFragmentManager(),getString(R.string.str_change_city),"定位到当前城市"+mLocationCity+"，是否切换当前城市？", "切换", "取消");
            dialog.setSubmit(new View.OnClickListener() {
                @Override
                public void onClick(View v) {//切换城市
                    dialog.dismiss();
                    mLocationManger.setCurCityBean(mLocationCity);
                    mCityTv.setText(mLocationManger.getCurCityName());
                    mMyApplication.mHVCitiesBean.setName(mLocationManger.getCurCityName());
                    EventBus.getDefault().post(new UiEvent(EventConstant.S_CITY_COURSE, null));
                    doRefreshChange();
                }
            });
            dialog.setCancel(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
        }
    }

    /**
     * 切换城市刷新数据
     */

    private void doRefreshChange() {
        mMainActivity.loadingView.show();
        refreshGymList();
        getProjects();
        getHomepageContent();
    }

    /**
     * 获取bannner
     */

    private void getHomepageContent() {
        ICommonService.getHomepageContent(getActivity(),mLocationManger.getCityCode(),false, new ObjectCallback<ArrayList<HVHomePageItemBean>>() {
            @Override
            public void onSuccess(ArrayList<HVHomePageItemBean> response, String message) {
                if (!StringUtils.isNull(mHVHomePageItemBeans)) {
                    mHVHomePageItemBeans.clear();
                }
                if (null != response) {
                    mCbBanner.setVisibility(View.VISIBLE);
                    mHVHomePageItemBeans.addAll(response);
                    doRefreshBanner(mHVHomePageItemBeans);
                }else{
                    mCbBanner.setVisibility(View.GONE);
                }
            }

            @Override
            public void onErrorT(int code, ArrayList<HVHomePageItemBean> response, String errorMessage) {

            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                Logger.e("getHomepageContent statusCode"+statusCode);
            }
        });
    }

    /**
     * banner 加载图片处理
     * @param hvHomePageItemBeans banner列表
     */

    private void doRefreshBanner(List<HVHomePageItemBean> hvHomePageItemBeans) {
        List<String> mBannerUrls=new ArrayList<>();//存放场馆Banner的url列表
        for(HVHomePageItemBean mBannerBean : hvHomePageItemBeans){
            mBannerUrls.add(mBannerBean.getPic());
        }
        mCbBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        },mBannerUrls).setPageIndicator(new int[]{R.mipmap.ic_page_indicator, R.mipmap.ic_page_indicator_focused});
        mCbBanner.setCanLoop(mBannerUrls.size()!=1);//设置是否循环
        mCbBanner.setPointViewVisible(mBannerUrls.size()!=1);//当只有一个的时候隐藏小点
    }


    private View.OnClickListener selectDateListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final ThreeWheelTimeDialog mChooseTimeShortDialog = new ThreeWheelTimeDialog(mContext, R.style.BottomToTopAnim);
            mChooseTimeShortDialog.setDate();
            mChooseTimeShortDialog.setOnClickSubmitListener(new WheelDialog.OnClickSubmitListener() {
                @Override
                public void onClickSubmit(String[] values, ThreeWheelBean threeWheelBean) {
                    wheelBean = threeWheelBean;
                    String emptyeS = StringUtils.stringAdd2Space(threeWheelBean.getDateStr());
                    SpannableStringBuilder sb = new SpannableStringBuilder(emptyeS); // 包装字体内容
                    ForegroundColorSpan fcs = new ForegroundColorSpan(getResources().getColor(R.color.c_333333)); // 设置字体颜色
                    AbsoluteSizeSpan ass = new AbsoluteSizeSpan(SizeUtils.dp2px(mContext, 16),false);  // 设置字体大小

                    sb.setSpan(fcs, 0, 2, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                    sb.setSpan(ass, 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    mTvDay.setText(sb);
                    if (threeWheelBean.isAllDay()) {
                        mTvtime.setText("全天");
                    } else {
                        mTvtime.setText(threeWheelBean.getStartTimeStr() + "-" + threeWheelBean.getEndTimeStr());
                    }
                }

                @Override
                public void onNotTimeSelect() {

                }
            });
            mChooseTimeShortDialog.show();
        }
    };

    /**
     * 获取全部运动
     */

    private void getProjects() {
        ICommonService.getProjects(getActivity(), mLocationManger.getCityCode(),false, new ObjectCallback<ArrayList<HVProjectBean>>() {
            @Override
            public void onHttpErrorCall(int statusCode) {
                Logger.e("getProjects statusCode"+statusCode);

            }

            @Override
            public void onSuccess(ArrayList<HVProjectBean> response, String message) {
                if (null != response || response.size() != 0) {
                    if(!StringUtils.isNull(mHVProjectBeans)){
                        mHVProjectBeans.clear();
                    }
                    mHVProjectBeans.addAll(response);
                    mMyApplication.mHVProjectBean = mHVProjectBeans;
                    initSpView();
                    initTabText();
                    if (curPos != 4) {//pos==4的时候为全部 不需要赋值
                        mHVProjectBean = mHVProjectBeans.get(curPos);//默认为第一个 最大初始化是4
                        mAllProjectManger.setHVProjectBeanList(mHVProjectBeans);//赋值
                        mViewSelected.setText(mHVProjectBean.getProjectName());//默认选中的View初始化
                    }
                }
            }

            @Override
            public void onErrorT(int code, ArrayList<HVProjectBean> response, String errorMessage) {

            }
        });
    }

    /**
     * 获取所有场馆列表
     */
    private void getVenueList() {
        IVenueService.getVenueList(getActivity(), mLocationManger.getCityCode(), mLocationManger.longitude, mLocationManger.latitude, null, null, null, "", mPageIndex, PAGESIZE, Enum.EnumVenueListType.All,"",null,false, new ObjectCallback<ArrayList<HVVenueBean>>() {
            @Override
            public void onHttpErrorCall(int statusCode) {
                mMainActivity.dialogDis();
                if(isRefresh){
                    mPfHome.refreshComplete();
                }else{
                    mPageIndex--;
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mLvAllGym, pageSize, LoadingFooter.State.NetWorkError, mFooterClick);
                }
            }

            @Override
            public void onSuccess(ArrayList<HVVenueBean> response, String message) {
                mMainActivity.dialogDis();
                if (!isRefresh) {
                    RecyclerViewStateUtils.setFooterViewState(mLvAllGym, LoadingFooter.State.Normal);

                } else {
                   mPfHome.refreshComplete();
                    mHVVenueBeans.clear();//刷新清空数据源
                }

                if (null != response && response.size() != 0) {
                    mHVVenueBeans.addAll(response);
                } else {
                    if(!isRefresh){
                        mPageIndex--;
                        RecyclerViewStateUtils.setFooterViewState(mLvAllGym, LoadingFooter.State.TheEnd);
                        isCanLoadMore=false;
                    }
                }
                mAllGymAdapter.notifyDataSetChanged();
                doFirstGoDetail();

            }

            @Override
            public void onErrorT(int code, ArrayList<HVVenueBean> response, String errorMessage) {
                mMainActivity.dialogDis();
                if(isRefresh){
                    if(null!=mPfHome){
                        mPfHome.refreshComplete();
                    }
                }else{
                    mPageIndex--;
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), mLvAllGym, pageSize, LoadingFooter.State.NetWorkError, mFooterClick);
                }
            }
        });
    }

    private void doFirstGoDetail() {
        if(mMainActivity.mUri!=null){
            String path = mMainActivity.mUri.getPath();
            String mDetailId=path.split("/")[2];
            String mDetailType=path.split("/")[1];
            if(mDetailType.equals("venue")){//跳转场馆详情
                goGymDetail(mDetailId);
            }else{
                goProductDetail(mDetailId);
            }
            mMainActivity.mUri=null;
        }
    }

    private void goProductDetail(String mProductId) {
        Intent intent = new Intent(mContext, ProductDetailsActivity.class);
        intent.putExtra("productId", mProductId);
        startActivity(intent, false);
    }

    /**
     * 设置tabText
     */

    private void initTabText() {
        for (int i = 0; i < mViewTab.getChildCount() - 1; i++) {//不包括全部
            HVProjectBean mProBean = null;
            TextView tabTextView = (TextView) mViewTab.getChildAt(i);
            if (mHVProjectBeans != null && i < mHVProjectBeans.size()) {//防止数组越界
                mProBean = mHVProjectBeans.get(i);
            }
            tabTextView.setText(null == mProBean ? "" : mProBean.getProjectName());

        }
    }

    /**
     * 启动选择的动画
     *
     * @param nextPos 下一个位置
     */
    private void doMoveSelected(int nextPos) {
        if (nextPos == curPos) {
            return;
        }
        mViewSelected.clearAnimation();
        ObjectAnimator.ofFloat(mViewSelected, "translationX", mViewTab.getChildAt(curPos).getX() - SizeUtils.dp2px(mContext, 10), mViewTab.getChildAt(nextPos).getX() - SizeUtils.dp2px(mContext, 10)).setDuration(200).start();//减去pading10dp
        //tab下面的运动的滑动
        float leftOrRight=curPos<nextPos?-1f:1f;//下一个位置的pos>当前的pos动画向右 否则向左
        //初始化动画
        //全部运动tab 下面的时间以及全部运动的动画mTaSport
        TranslateAnimation mTaSport = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF, leftOrRight, TranslateAnimation.RELATIVE_TO_SELF,0f , TranslateAnimation.RELATIVE_TO_SELF, 0f, TranslateAnimation.RELATIVE_TO_SELF, 0f);
        mTaSport.setDuration(200);// 设置动画执行时间
        mLlTime.clearAnimation();//清除动画
        mLlTime.startAnimation(mTaSport);
        curPos = nextPos;
    }

    /**
     * 测量单个distance
     */
    private void measureDistace() {
        singleDistance = (ScreenUtils.getScreenWidth(getActivity()) - SizeUtils.dp2px(mContext, 50)) / 5;
    }

    /**
     * 初始化Banner
     */
    public void initBanner() {
        mCbBanner.setCanLoop(true);
        mCbBanner.setPointViewVisible(true);
        mCbBanner.setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT,0,0, com.bigkoo.convenientbanner.utils.SizeUtils.dp2px(getActivity(),15), com.bigkoo.convenientbanner.utils.SizeUtils.dp2px(getActivity(),43));
        mCbBanner.startTurning(Constants.BANNER_TIME);//轮播设为3秒
    }

    /**
     * 初始化全运动的View
     */
    private void initSpView() {
        //总的页数=总数/每页数量，并取整
//        mVpSPAll.removeAllViews();
        pageCount = (int) Math.ceil(mHVProjectBeans.size() * 1.0 / pageSize);
        mSpPagerList.clear();
        for (int i = 0; i < pageCount; i++) {
            //每个页面都是inflate出一个新实例
            GridView gridView = (GridView) LayoutInflater.from(mContext).inflate(R.layout.gridview, mVpSPAll, false);
            gridView.setAdapter(new AllSpAdapter(mContext, mHVProjectBeans, i, pageSize));
            mSpPagerList.add(gridView);

            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    int pos = position + curIndex * pageSize;
                    mHVProjectBean = mHVProjectBeans.get(pos);
                    goFindPalce(sBOOK_ALL);

                    // 统计各项点击次数
                    HashMap<String, String> map = new HashMap<>();
                    map.put("projectId", mHVProjectBean.getProjectId());
                    StatisticsManager.onEvent(mContext, StatisticsManager.HomePage_SportsTag, map);
                }
            });
        }

        mVPAllSport.notifyDataSetChanged();
//        mVpSPAll.setCurrentItem(0);
        //设置圆点
        setOvalLayout();
    }

    /**
     * 设置圆点
     */
    public void setOvalLayout() {
        mLlSpDos.removeAllViews();
        for (int i = 0; i < pageCount; i++) {
            mLlSpDos.addView(LayoutInflater.from(mContext).inflate(R.layout.dot, null));
        }
        if (1 == pageCount) {//只有一页隐藏
            mLlSpDos.setVisibility(View.GONE);
        } else
            mLlSpDos.setVisibility(View.VISIBLE);
        // 默认显示第一页
        if(pageCount<=curIndex){
            mLlSpDos.getChildAt(pageCount-1).findViewById(R.id.v_dot)
                    .setBackgroundResource(R.drawable.dot_focused_blue);
        }else {
            mLlSpDos.getChildAt(curIndex).findViewById(R.id.v_dot)
                    .setBackgroundResource(R.drawable.dot_focused_blue);
        }
       /* mLlSpDos.getChildAt(0).findViewById(R.id.v_dot)
                .setBackgroundResource(R.drawable.dot_focused_blue);*/
        mVpSPAll.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            public void onPageSelected(int position) {
                // 取消圆点选中
                mLlSpDos.getChildAt(curIndex)
                        .findViewById(R.id.v_dot)
                        .setBackgroundResource(R.drawable.dot_normal);
                // 圆点选中
                mLlSpDos.getChildAt(position)
                        .findViewById(R.id.v_dot)
                        .setBackgroundResource(R.drawable.dot_focused_blue);
                curIndex = position;
            }

            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    /**
     * 全部场馆
     */
    public void initAllGym() {
        mLinearLayoutManager=new LinearLayoutManager(mContext);
        mLvAllGym.setLayoutManager(mLinearLayoutManager);
        mAllGymAdapter = new GymsRecyclertAdapter(mContext,mHVVenueBeans);
        mAllGymAdapter.setHeadView(mHomeHeadView);
        mAllGymAdapter.setOnItemClickLitener(new OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                goGymDetail(mHVVenueBeans.get(position).getVenueId());
            }
        });
        HeaderAndFooterRecyclerViewAdapter headerAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mAllGymAdapter);
        mLvAllGym.setAdapter(headerAndFooterRecyclerViewAdapter);
        mLvAllGym.addOnScrollListener(mOnScrollListener);
    }

    private void goGymDetail(String venueId) {
        Bundle mBundle = new Bundle();
        mBundle.putString(Constants.FLAG_INTENT_VENUEID, venueId);
        startActivity(GymDetailActivity.class, mBundle, false);
    }

    /**
     * 去找场地
     * @param type 全部 产品 预定
     */

    private void goFindPalce(int type) {
        Bundle mBundle = new Bundle();
        mBundle.putString(Constants.FLAG_INTENT_PROJECTID, null == mHVProjectBean ? "" : mHVProjectBean.getProjectId());//id
        mBundle.putString(Constants.FLAG_INTENT_PROJECTNAME, null == mHVProjectBean ? "" : mHVProjectBean.getProjectName());//name
        mBundle.putSerializable(Constants.WHEELBEAN_TALG, wheelBean);
        mBundle.putInt(Constants.BOOK_TYPE,type);
        mBundle.putBoolean(Constants.KEY_IS_GYM_SEARCH,true);
        startActivity(SearchResultActivity.class, mBundle, false);
    }

    /**
     * 跳转搜索页面
     */
    @OnClick(R.id.iv_search)
    public void onImgRightClick() {
        StatisticsManager.onEvent(mContext, StatisticsManager.HomePage_Search);
        Bundle mBundle=new Bundle();
        mBundle.putBoolean(Constants.KEY_IS_GYM_SEARCH,true);
        startActivity(SearchActivity.class,mBundle, false);
    }

    /**
     * EventBus 接收事件
     *
     * @param uiEvent
     */
    @Subscribe
    public void getCity(UiEvent uiEvent) {
        if (uiEvent.getKey().equals(EventConstant.S_CITY)) {//选择城市
            mCityTv.setText(mLocationManger.getCurCityName());
            doRefreshChange();
        }else if(EventConstant.S_MYINFO.equals(uiEvent.getKey())){//登录后刷新列表
            refreshGymList();
        }
    }

    public void setCityRightDrable() {
        Drawable drawable = getResources().getDrawable(R.drawable.city_other);
        /**这一步必须要做,否则不会显示.*/
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());//对图片进行压缩

        /**设置图片位置，四个参数分别方位是左上右下，都设置为null就表示不显示图片*/
        mCityTv.setCompoundDrawables(null, null, drawable, null);
    }
    /**
     * 获取本地数据
     */

    private void getLocalCurrCity() {
        String strCurrCity = FileUtils.readFile2String(mCurrCity, FileConstant.CHARSET_NAME);
        mHVCitiesBean = mGson.fromJson(strCurrCity, HVCitiesBean.class);

    }

    /**
     * 获取城市列表
     */

    private void getCityData() {
        ICommonService.getCities(getActivity(), true, new ObjectCallback<ArrayList<HVCitiesBean>>() {
            @Override
            public void onSuccess(ArrayList<HVCitiesBean> response, String message) {
                if (null != response && response.size() != 0) {
                    mHVCitiesBeens.addAll(response);
//                    mMyApplication.mHVCitiesBean = mHVCitiesBeens.get(0);
                    for (HVCitiesBean mHVCitiesBean : mHVCitiesBeens) {
                        if (mHVCitiesBean.getName().equals("杭州")) {//默认杭州
                            mMyApplication.mHVCitiesBean = mHVCitiesBean;
                            mCityTv.setText(mHVCitiesBean.getName());
                            EventBus.getDefault().post(new UiEvent(EventConstant.S_CITY_COURSE, mHVCitiesBean));
                            FileUtils.writeFileFromString(mCurrCity, mGson.toJson(mHVCitiesBean), false);//将默认数据写入文件
                        }
                    }
                    FileUtils.writeFileFromString(file, mGson.toJson(mHVCitiesBeens), false);//将城市数据写入文件
                }
            }

            @Override
            public void onErrorT(int code, ArrayList<HVCitiesBean> response, String errorMessage) {
                Logger.e("errorMessage");

            }

            @Override
            public void onHttpErrorCall(int statusCode) {
                Logger.e("statusCode");
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mLlTime) {//清除动画
            mLlTime.clearAnimation();
        }
        EventBus.getDefault().unregister(this);//销毁的时候注销EventBus
    }


    /**
     * 场馆刷新
     */

    public void refreshGymList(){
        mPageIndex = 1;
        isCanLoadMore=true;
        isRefresh= true;
        getVenueList();
        mScrollHight=0;//滚动距离置0
    }

    /**
     * 场馆下拉加载
     */
    public void loadMoreGymList(){
        mPageIndex++;
        isRefresh=false;
        getVenueList();
    }

    /**
     * Banner的点击事件
     */

    @Override
    public void onBannerClick(int position) {
        doBannerClick(position);
    }

    /**
     * banner的点击事件
     * @param position pos
     */

    private void doBannerClick(int position) {
        //处理图片的点击事件 一般是跳转到广告的详情界面
        HVClickInfoBean clickInfo =mHVHomePageItemBeans.get(position).getClickInfo();
        if(!StringUtils.isNull(clickInfo)) {
            Enum.EnumHomepageAction action = clickInfo.getAction();

            String key = StatisticsManager.HomePage_banner;
            // 统计各项点击次数
            HashMap<String, String> map = new HashMap<>();
            map.put("bannerId", clickInfo.getBannerId() + "");
            StatisticsManager.onEvent(mContext, key, map);

            if(!StringUtils.isNull(clickInfo.getUrl())) {
                String[] gymIds = clickInfo.getUrl().split(";");
                if(gymIds!=null&&gymIds.length>0) {
                    bannerIntentManger.bannerIntent(clickInfo,action,clickInfo.getTitle(), gymIds);
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_find_place:
                StatisticsManager.onEvent(mContext, StatisticsManager.HomePage_Find);
                goFindPalce(sBOOK_GYM);
                break;
            case R.id.fab_back_to_top:
                mLinearLayoutManager.scrollToPosition(0);
                AnimotionUtils.onHide(mBackToTop);
                mScrollHight=0;
                break;
        }
    }


    /**
     * 上拉加载监听
     */

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            if(StringUtils.isNull(mLvAllGym)){
                return;
            }
            LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(mLvAllGym);
            if(state == LoadingFooter.State.Loading) {
                return;
            }

            if (isCanLoadMore) {
                // loading more
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mLvAllGym, pageSize, LoadingFooter.State.Loading, null);
                loadMoreGymList();
            } else {
                //the end
                RecyclerViewStateUtils.setFooterViewState(getActivity(), mLvAllGym, pageSize, LoadingFooter.State.TheEnd, null);
            }
        }
    };

    public int getScollYDistance() {
        int position = mLinearLayoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = mLinearLayoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }

    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RecyclerViewStateUtils.setFooterViewState(getActivity(), mLvAllGym, pageSize, LoadingFooter.State.Loading, null);
            loadMoreGymList();
        }
    };
}
